package com.bobbygu.server.simpleapp.controller;

import com.bobbygu.server.simpleapp.mapper.HomeMapper;
import com.bobbygu.server.simpleapp.model.HomeAdImgModel;
import com.bobbygu.server.simpleapp.model.ImgModel;
import com.bobbygu.server.simpleapp.model.response.BaseResponse;
import com.bobbygu.server.simpleapp.model.response.ConstResponse;
import com.bobbygu.server.simpleapp.model.response.ResultResponse;
import com.bobbygu.server.simpleapp.model.response.StringResponse;
import com.bobbygu.server.simpleapp.utils.FileUtils;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

@RestController
public class HomeController {
    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private HomeMapper homeMapper;

    @RequestMapping(value = "/home/UploadHomeAdImg.do", method = RequestMethod.POST)
    public BaseResponse upload(MultipartHttpServletRequest multiReq) throws IOException, ServletException {
        System.out.println("upload");
//        final String imgName = "ImgData";
        String rootPath = multiReq.getSession().getServletContext().getRealPath("/");
        final String ROOT_IMG_FOLDER = "imageDir";
        final String ROOT = rootPath + ROOT_IMG_FOLDER;

        Iterator<String> itr = multiReq.getFileNames();
        while (itr.hasNext()) {
            String name = itr.next();
            FileInputStream fs = (FileInputStream) multiReq.getPart(name).getInputStream();
            HomeAdImgModel imgModel = homeMapper.findImgByName(name);
            try {
                Path path = Paths.get(ROOT, name);
                System.out.println(ROOT);
                System.out.println(path.toAbsolutePath().toString());
                if (!path.toFile().exists())
                    FileUtils.createFile(path.toString());
                Files.delete(path);
                Files.copy(fs, path);
                System.out.println(" Files.copy success!");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(" Files.copy fail!");
            }
            if (imgModel != null) {
                homeMapper.updateImg(name, ROOT_IMG_FOLDER, input2byte(fs));
            } else {
                homeMapper.insertImg(name, ROOT_IMG_FOLDER, input2byte(fs));
            }
        }

//        FileInputStream fs = (FileInputStream) multiReq.getPart(imgName).getInputStream();
//
//        HomeAdImgModel imgModel = homeMapper.findImgByName(imgName);
//        try {
//            Path path = Paths.get(ROOT, imgName + ".jpg");
//            System.out.println(ROOT);
//            System.out.println(path.toAbsolutePath().toString());
//            if (!path.toFile().exists())
//                FileUtils.createFile(path.toString());
//            Files.delete(path);
//            Files.copy(fs, path);
//            System.out.println(" Files.copy success!");
//        } catch (IOException e) {
//            e.printStackTrace();
//            System.out.println(" Files.copy fail!");
//        }
//        if (imgModel != null) {
//            homeMapper.updateImg(imgName, ROOT);
//        } else {
//            homeMapper.insertImg(imgName, ROOT);
//        }

        return new ResultResponse(new StringResponse("上传成功"), ConstResponse.DESC_OK, ConstResponse.STATUS_OK);
    }

    @RequestMapping(value = "/home/GetHomeAdImgList.do", method = RequestMethod.POST)
    public BaseResponse GetHomeAdImgList() {
        System.out.println("GetHomeAdImgList.do");
        return new ResultResponse(homeMapper.selectAll(), ConstResponse.DESC_OK, ConstResponse.STATUS_OK);
    }

    @RequestMapping(value = "/home/DeleteImgByName.do", method = RequestMethod.POST)
    public BaseResponse DeleteImgByName(@RequestBody Map<String, Object> requestMap) {
        System.out.println("DeleteImgByName.do");
        if (requestMap.get("Name") == null) {
            return new BaseResponse("Name 不能为空", ConstResponse.STATUS_PARAM_ERROR);
        }
        String name = requestMap.get("Name").toString();
        if (name != null) {
            homeMapper.deleteImgByName(name);
            return new BaseResponse(ConstResponse.DESC_OK, ConstResponse.STATUS_OK);
        } else {
            return new BaseResponse(ConstResponse.DESC_PARAM, ConstResponse.STATUS_PARAM_ERROR);
        }
    }

    private InputStream byte2Input(byte[] buf) {
        return new ByteArrayInputStream(buf);
    }

    private byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }
}
